package com.qfedu.dtboot.service.impl;

import com.qfedu.dtboot.entity.ScheduleJob;
import com.qfedu.dtboot.dao.ScheduleJobDao;
import com.qfedu.dtboot.service.ScheduleJobService;
import com.qfedu.dtboot.util.Constant;
import com.qfedu.dtboot.util.DataGridResult;
import com.qfedu.dtboot.util.R;
import com.qfedu.dtboot.util.SchedulerUtils;
import io.swagger.models.auth.In;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 定时任务(ScheduleJob)表服务实现类
 *
 * @author ykx
 * @since 2022-09-27 13:04:17
 */
@Service
public class ScheduleJobServiceImpl implements ScheduleJobService {

    @Autowired
    private ScheduleJobDao scheduleJobDao;

    @Autowired
    private Scheduler scheduler;

    @Override
    public DataGridResult queryJobList(Map<String, Object> params) {
        List<ScheduleJob> rows = scheduleJobDao.queryAllJobByLimit(params);
        Integer total = scheduleJobDao.queryJobCount();
        return new DataGridResult(rows,total);
    }

    @Override
    public R saveJob(ScheduleJob scheduleJob) {
        Integer insert = scheduleJobDao.insert(scheduleJob);
        //创建定时任务
        SchedulerUtils.createJob(scheduler, scheduleJob);
        return insert>0?R.ok(): R.error();
    }

    @Override
    public R updateJob(ScheduleJob scheduleJob) {
        SchedulerUtils.updateJob(scheduler, scheduleJob);
        return scheduleJobDao.update(scheduleJob)>0?R.ok():R.error();
    }

    @Override
    public R getJobInfoById(Long jobId) {
        return R.ok().put("scheduleJob",scheduleJobDao.queryById(jobId));
    }

    @Override
    public R delBatchJobs(Long[] ids) {
        return scheduleJobDao.deleteBatch(ids)>0?R.ok():R.error();
    }

    @Override
    public R pauseJobs(Long[] ids) {
        for(Long jobId : ids){
            SchedulerUtils.pauseJob(scheduler, jobId);
        }
        return scheduleJobDao.updateStatusBatch(ids,true)>0?R.ok(): R.error();
    }

    @Override
    public R resumeJobs(Long[] ids) {
        for(Long jobId : ids){
            SchedulerUtils.resumeJob(scheduler, jobId);
        }
        return scheduleJobDao.updateStatusBatch(ids,false)>0?R.ok():R.error();
    }
}
